# list.tcl - procedures for handling response from
# the /LIST command and other related functions

# CONTENTS:
# 	listview {chid raw parent me}
#		Listener for the numeric 321. Creates the channel list
#		window ready to take content.
#
#	appendlist {chid raw parent me}
#		Listener for the numeric 322. Adds content
#		for the channel list.
#
#	listview_join {}
#		Gets the selected channels from the treeview, and
#		sends join requests for them. Procedure takes no arguments,
#		is a button press callback.
#
#	sendlist {}
#		Sends a /LIST to the server currently as the active
#		server tab. Procedure takes no arguments, is a button press
#		callback.

# Who said only modules can register
# themselves in $RECV_LISTEN? :-)
set RECV_LISTEN(321) listview
set RECV_LISTEN(322) appendlist

proc listview {chid raw parent me} {
	global IMAGES LIST_CHID n_conns conns
	
	set LIST_CHID $chid
	
	toplevel	.listdlg
	
	wm title .listdlg [tr "Channel list"]
	
	ttk::frame	.listdlg.toolbar
	ttk::treeview	.listdlg.lview \
		-columns {channel users topic} \
		-yscrollcommand {.listdlg.yscroll set} \
		-height 20
	
	ttk::scrollbar	.listdlg.yscroll -command {.listdlg.lview yview}
	ttk::button	.listdlg.join	 -text [tr "Join"]
	ttk::button	.listdlg.close	 -text [tr "Close"]
	
	.listdlg.lview heading channel	 -text [tr "Channel"]
	.listdlg.lview heading users	 -text [tr "Users"]
	.listdlg.lview heading topic	 -text [tr "Topic"]
	
	.listdlg.lview configure -show {headings}
	
	grid columnconfigure .listdlg 0 -weight 1
	grid rowconfigure .listdlg 0 -weight 1
	
	grid \
		[ttk::button .listdlg.toolbar.connect -compound top -style Toolbutton \
		-text "Join" -command listview_join \
		-image $IMAGES(add)]
	
	grid .listdlg.toolbar	-row 0 -column 0 -columnspan 2 -sticky w
	grid .listdlg.lview	-row 1 -column 0 -sticky nsew
	grid .listdlg.yscroll	-row 1 -column 1 -sticky nsw
	
	raw $LIST_CHID "LIST"
}

proc appendlist {chid raw parent me} {
	puts [regexp {[^ ]+ 322 [^ ]+ ([^ ]+) ([0-9]+) :(.+)} $raw -> channel users topic]
	
	.listdlg.lview insert {} end -values "{$channel} $users {$topic}"
}

proc listview_join {} {
	global LIST_CHID
	
	foreach item [.listdlg.lview selection] {
		set channel [lindex [.listdlg.lview item $item -values] 0]
		raw $LIST_CHID "JOIN $channel";
	}
}

proc sendlist {} {
	raw [getchid] "LIST"
}

